from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
import jsonrpclib
import RPIO as GPIO
import time
import threading
import random

id = 42
def set_id(arg_id):
    id = arg_id

def unlock_bike(unlock_time):
	print "Unlocking bike for %i seconds!" %unlock_time
	GPIO.output(17, False)
	time.sleep(unlock_time)
	print "Set Output True"
	GPIO.output(17, True)
	time.sleep(1)
def lock_bike():
    GPIO.output(17, True)

def status(foo):
	GPIO.output(27, True)
	time.sleep(1)
	GPIO.output(27, False)
	time.sleep(1)
	GPIO.output(27, True)
	time.sleep(1)
	GPIO.output(27, False)
	time.sleep(1)
	return "AWAKE and fully functional"

remote = jsonrpclib.Server("http://192.168.1.22:4242")
status = False
def battery_alarm(gpio_id,value):
    foo = random.randint(0,10)
    if foo >5:
        status = False
    else:
        status = True
    GPIO.output(24, status)
    remote.battery_alert(id,random.randint(5,100))

GPIO.setmode(GPIO.BCM)
 
print "Setupping GPIO"
GPIO.setup(17, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(23, GPIO.IN)

GPIO.output(17, True)
GPIO.output(24, True)
GPIO.output(25, True)
GPIO.output(27, False)


GPIO.wait_for_interrupts(threaded=True)
GPIO.add_interrupt_callback(23, battery_alarm,edge='rising',pull_up_down=GPIO.PUD_UP)


server = SimpleJSONRPCServer(('0.0.0.0', 8081))
server.register_function(lambda x : unlock_bike(x), 'unlock')
server.register_function(lock_bike(), 'lock')
server.register_function(lambda x : status(x), 'status')
server.register_function(lambda x : set_id(x),'set_id') 
server.serve_forever()

